//
//  PhoneRegisterViewController.m
//  GBKTrade
//
//  Created by LionIT on 14/03/2018.
//  Copyright © 2018 LionIT. All rights reserved.
//

#import "GSRegisterViewController.h"
#import "UIButton+Extension.h"
#import "MQVerCodeInputView.h"
#import "RegisterTextField.h"
#import "QCheckBox.h"
#import "NSString+Custom.h"
#import "SZHttpsService.h"
#import "NSString+Helper.h"
@interface GSRegisterViewController ()<QCheckBoxDelegate,UITextFieldDelegate> {
    NSTimer *_timer;
    int nSecond;
}
@property (nonatomic,strong) RegisterTextField *txtPwd;

@property (nonatomic,strong) RegisterTextField *txtConfirmPwd;

@property (nonatomic,strong) RegisterTextField* phoneTx;

@property (nonatomic,strong) RegisterTextField* msgCodeTx;

@property (nonatomic,strong) UIButton* sendCodeBtn;

@property (nonatomic,strong) RegisterTextField* recommendCodeTx;

//同意
@property (nonatomic,strong) QCheckBox * checkAgree;
//重发验证码

@property (nonatomic,strong) UIButton * btnCode;
//注册
@property (nonatomic,strong) UIButton * signUpBtn;
//
@property (nonatomic,copy) NSString * validateCode;


@end

@implementation GSRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.headView.backgroundColor = WhiteColor;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.btnLeft setImage:YQ_IMAGE(@"nav_back_white") forState:UIControlStateNormal];
    
    [self initUIHead];
}

- (void)initUIHead {
    
    UILabel * loginLabel = [[UILabel alloc] init];
    [loginLabel setFont:[UIFont boldSystemFontOfSize:30]];
    [loginLabel setTextColor:color_333333];
    loginLabel.text = self.regType == 0 ? NSLocalizedString(@"手机注册", nil) : NSLocalizedString(@"邮箱注册", nil);
    [loginLabel setTextAlignment:NSTextAlignmentLeft];
    [self.view addSubview:loginLabel];
    [loginLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(FIT(20));
        make.top.equalTo(self.headView.mas_bottom).offset(30);
    }];
    
    
    RegisterTextField* addressTextField=[RegisterTextField new];
    addressTextField.placeholder=NSLocalizedString(@"请输入手机号码", nil);
    addressTextField.textColor=[UIColor blackColor];
    addressTextField.font=[UIFont systemFontOfSize:14.0f];
    self.phoneTx=addressTextField;
    [self.view addSubview:addressTextField];
    [addressTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(loginLabel.mas_bottom).offset(FIT(40));
        make.left.mas_equalTo(FIT(20));
        make.width.mas_equalTo(ScreenWidth-FIT(20)*2);
        make.height.mas_equalTo(FIT(60));
    }];
    
    
    UIView* remarkView=[UIView new];
    remarkView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:remarkView];
    [remarkView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(addressTextField.mas_bottom);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(ScreenWidth);
        make.height.mas_equalTo(FIT(60));
    }];
    
    
    RegisterTextField* remarkTextField=[RegisterTextField new];
    remarkTextField.placeholder=NSLocalizedString(@"请输入验证码", nil);
    remarkTextField.textColor=[UIColor blackColor];
    remarkTextField.font=[UIFont systemFontOfSize:14.0f];
    [remarkView addSubview:remarkTextField];
    self.msgCodeTx=remarkTextField;
    [remarkTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(FIT(20));
        make.width.mas_equalTo(ScreenWidth-FIT(20)*2);
        make.height.mas_equalTo(FIT(60));
    }];
    UIButton* saoButton=[UIButton new];
    [saoButton.titleLabel setFont:[UIFont systemFontOfSize:14.0f]];
    [saoButton.titleLabel setTextAlignment:NSTextAlignmentCenter];
    [saoButton setTitle:NSLocalizedString(@"发送", nil) forState:UIControlStateNormal];
    [saoButton setTitleColor:MainThemeColor forState:UIControlStateNormal];
    [remarkView addSubview:saoButton];
    self.sendCodeBtn=saoButton;
    [self.sendCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(FIT(-20));
        make.top.equalTo(remarkTextField.mas_top);
        make.height.mas_equalTo(FIT(60));
        make.width.mas_equalTo(FIT(50));
        
    }];
    
    @weakify(self);
    [[self.sendCodeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        
        @strongify(self);
        if (self.phoneTx.text.length == 0) {
            [LCProgressHUD showFailure: @"手机号码"];
            return;
        }
        
        __block NSInteger seconds=0;
        __block RACSignal* timerSignal;
//        [LCProgressHUD showLoading:<#(NSString *)#>];
        
        [[[SZHttpsService sharedSZHttpsService] signalRequestMsgCodeWithParameters:@{@"phoneNum":self.phoneTx.text,@"countryCode":@"86",@"msgType":@(1)}]subscribeNext:^(id x) {
//            [self hideMBProgressHUD];
            if ([x isKindOfClass:[NSDictionary class]]) {
                BaseModel * baseModel = [[BaseModel alloc] initWithDictionary:x error:nil];
                
                if (SuccessCode == baseModel.code) {
                    [LCProgressHUD showMessage:@"验证码已发送,请查收"];
                    seconds=120;
                    [saoButton setTitle:FormatString(@"%lds",(long)seconds) forState:UIControlStateNormal];
                    if (!timerSignal) {
                        timerSignal=[[RACSignal interval:1.0f onScheduler:[RACScheduler mainThreadScheduler]]takeUntil:self.rac_willDeallocSignal];
                        [timerSignal subscribeNext:^(id x) {
                            seconds--;
                            if (seconds <= 0) {
                                [saoButton setTitle:NSLocalizedString(@"发送", nil) forState:UIControlStateNormal];
                            }else{
                                [saoButton setTitle:FormatString(@"%lds",(long)seconds) forState:UIControlStateNormal];
                            }
                        }];
                    }else{
                        [timerSignal startWith:@0];
                    }
                    
                   
                } else {
                    [LCProgressHUD showFailure:baseModel.msg];
                }
            }
        }error:^(NSError *error) {
            [LCProgressHUD showFailure:error.localizedDescription];
//            [self showErrorHUDWithTitle:error.localizedDescription];

        }];
        
        
    }];
    
    
//    UIColor *color = UIColorFromRGB(0xB2B2B2);
    _txtPwd = [[RegisterTextField alloc] initWithFrame:CGRectZero];
    _txtPwd.delegate = self;
//    [_txtPwd addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_txtPwd setBorderStyle:UITextBorderStyleNone];
    [_txtPwd setReturnKeyType:UIReturnKeyDone];
    _txtPwd.clearButtonMode = UITextFieldViewModeWhileEditing;
    _txtPwd.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _txtPwd.leftViewMode = UITextFieldViewModeAlways;
    [_txtPwd setBackgroundColor:[UIColor clearColor]];
//    [_txtPwd setTextColor:UIColorFromRGB(0x343434)];
    _txtPwd.isShowTextBool = YES;
//    _txtPwd.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"密码",nil) attributes:@{NSForegroundColorAttributeName:color}];
    _txtPwd.placeholder=NSLocalizedString(@"请输入密码", nil);
    _txtPwd.tag = 2;
    [_txtPwd setSecureTextEntry:YES];
    [_txtPwd setFont:XCFONT(15)];
    [_txtPwd setKeyboardType:UIKeyboardTypeASCIICapable];
    [self.view addSubview:_txtPwd];
    [_txtPwd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(remarkView.mas_bottom);
        make.leading.equalTo(loginLabel);
        make.trailing.equalTo(self.view).offset(-FIT(20));
        make.height.mas_equalTo(FIT(60));
    }];
    
  
    
    _txtConfirmPwd = [[RegisterTextField alloc] initWithFrame:CGRectZero];
    _txtConfirmPwd.delegate = self;
//    [_txtConfirmPwd addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_txtConfirmPwd setBorderStyle:UITextBorderStyleNone];
    [_txtConfirmPwd setReturnKeyType:UIReturnKeyDone];
    _txtConfirmPwd.clearButtonMode = UITextFieldViewModeWhileEditing;
    _txtConfirmPwd.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _txtConfirmPwd.leftViewMode = UITextFieldViewModeAlways;
    [_txtConfirmPwd setBackgroundColor:[UIColor clearColor]];
//    [_txtConfirmPwd setTextColor:UIColorFromRGB(0x343434)];
    _txtConfirmPwd.isShowTextBool = YES;
//    _txtConfirmPwd.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"确认密码",nil) attributes:@{NSForegroundColorAttributeName:color}];
    _txtConfirmPwd.placeholder=NSLocalizedString(@"请输入确认密码", nil);

    _txtConfirmPwd.tag = 2;
    [_txtConfirmPwd setSecureTextEntry:YES];
    [_txtConfirmPwd setFont:XCFONT(15)];
    [_txtConfirmPwd setKeyboardType:UIKeyboardTypeASCIICapable];
    [self.view addSubview:_txtConfirmPwd];
    [_txtConfirmPwd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_txtPwd.mas_bottom);
        make.leading.trailing.equalTo(_txtPwd);
        make.height.mas_equalTo(FIT(60));
    }];
    
   
    RegisterTextField* recommendCodeTx=[RegisterTextField new];
    recommendCodeTx.placeholder=NSLocalizedString(@"请输入邀请码", nil);
    recommendCodeTx.textColor=[UIColor blackColor];
    recommendCodeTx.font=[UIFont systemFontOfSize:14.0f];
    self.recommendCodeTx=recommendCodeTx;
    [self.view addSubview:recommendCodeTx];
    [recommendCodeTx mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_txtConfirmPwd.mas_bottom);
        make.left.mas_equalTo(FIT(20));
        make.width.mas_equalTo(ScreenWidth-FIT(20)*2);
        make.height.mas_equalTo(FIT(60));
    }];

    _signUpBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_signUpBtn setBackgroundImage:YQ_IMAGE(@"btnImg") forState:UIControlStateNormal];
//    _signUpBtn.backgroundColor = MainThemeColor;
    [_signUpBtn setTitle:NSLocalizedString(@"注册", nil) forState:UIControlStateNormal];
    [_signUpBtn setTitleColor:WhiteColor];
    _signUpBtn.titleLabel.font = YQ_Font(kNormalButtonFont);
    [_signUpBtn addTarget:self action:@selector(signUpAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_signUpBtn];
    [_signUpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(_txtConfirmPwd);
        make.top.equalTo(recommendCodeTx.mas_bottom).offset(FIT(30));
        make.height.mas_equalTo(44);
    }];
    [_signUpBtn setCircleBorderWidth:FIT(1) bordColor:[UIColor clearColor] radius:FIT(2)];


}


#pragma mark 注册
- (void)signUpAction:(UIButton *)sender {
    
    if (isEmptyString(self.phoneTx.text) || ![self.phoneTx.text isMobliePhone]) {
        [LCProgressHUD showMessage:@"请输入合法的手机号码"];
        return;
    }else if (isEmptyString(self.msgCodeTx.text) || self.msgCodeTx.text.length == 0){
        [LCProgressHUD showMessage:@"请输入验证码"];
        
        return ;
    }else if (self.txtPwd.text.length <=0 || self.txtConfirmPwd.text <=0) {
        [LCProgressHUD showMessage:@"请输入6-16位字母、数字组合的密码"];
        return;
    }else if (![[self.txtPwd.text trim] isEqualToString:[self.txtConfirmPwd.text trim]]) {
        [LCProgressHUD showMessage:@"密码不一致,请重新输入"];
        return;
    }else if(self.txtPwd.text.length < 6 || self.txtPwd.text.length > 16){
        [LCProgressHUD showMessage:@"请输入6-16位字母、数字组合的密码"];
        return ;
    }else if (self.txtPwd.text.length >= 6) {
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        BOOL result = [pred evaluateWithObject:self.txtPwd.text];
        if (!result) {
            [LCProgressHUD showMessage:@"请输入6-16位字母、数字组合的密码"];
            return ;
        }
    }
    
    
    if (isEmptyString(self.recommendCodeTx.text) || self.recommendCodeTx.text.length == 0){
        [LCProgressHUD showMessage:@"请输入邀请码"];
        return ;
    }
    
    
//    [self showLoadingMBProgressHUD];
    NSMutableDictionary *mDict = [[NSMutableDictionary alloc] initWithCapacity:6];
    NSString * md5Pwd = [AppUtil md5:[self.txtPwd.text trim]];
    [mDict setValue:md5Pwd forKey:@"password"];
    [mDict setValue:self.phoneTx.text forKey:@"phoneNum"];
    [mDict setValue:self.recommendCodeTx.text forKey:@"referralCode"];
    [mDict setValue:self.msgCodeTx.text forKey:@"messageCode"];
    [mDict setValue:@"86" forKey:@"countryCode"];
    
    
    [[SZHttpsService sharedSZHttpsService] registerAccount:mDict success:^(id responseObject) {
//        [self hideMBProgressHUD];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            BaseModel * baseModel = [[BaseModel alloc] initWithDictionary:responseObject error:nil];
            
            if (SuccessCode == baseModel.code) {
                [LCProgressHUD showMessage:baseModel.msg];
                [[SZSundriesCenter instance] delayExecutionInMainThread:^{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }];
            } else {
                [LCProgressHUD showMessage:baseModel.msg];
            }
        }
    } fail:^(NSError *error) {
        [LCProgressHUD showFailure:error.localizedDescription];
    }];
}

#pragma mark 显示协议
- (void)showDetailAgreementAction:(UIButton *)sender {
    
   
    
}


//#pragma mark - UITextFieldDelegate
//- (void)textFieldDidChange:(UITextField *)sender
//{
//    [self checkLogBtnIsEnable];
//}
//
//- (BOOL)textFieldShouldReturn:(UITextField *)textField
//{
//    [self checkLogBtnIsEnable];
//
//    return YES;
//}

//#pragma mark - QCheckBoxDelegate
//- (void)didSelectedCheckBox:(QCheckBox *)checkbox checked:(BOOL)checked {
//    checkbox.checked = checked;
//    [self checkLogBtnIsEnable];
//}
//
//#pragma mark - 检查输入情况以设置注册的可用性
//- (void)checkLogBtnIsEnable {
//    if (6 ==  [self.msgCodeTx.text trim].length   && 11 ==  [self.phoneTx.text trim].length && [self.txtPwd.text trim].length > 0 && [self.txtConfirmPwd.text trim].length > 0 && /*self.checkAgree.checked &&*/ [self.recommendCodeTx.text trim].length>0 ) {
//        self.signUpBtn.enabled = YES;
//        [self.signUpBtn setGradientBackGround];
//    } else {
//        self.signUpBtn.enabled = NO;
//        self.signUpBtn.backgroundColor = color_d2d2d2;
//        [self.signUpBtn removeGradientBackGround];
//    }
//}

#pragma mark - 切换到登录
//- (void)loginAction:(UIButton *)sender {
//    [self.navigationController popToRootViewControllerAnimated:YES];
//}
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}
@end
